"""
@author: forward
@date: 2023/09/01
@desc: 启动服务

"""

import os
from contextlib import asynccontextmanager

from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles

from forward.api.admin.app import create_admin
from forward.api.h5.app import create_h5
from forward.config import get_settings
from forward.utils.log import setup_logger


@asynccontextmanager
async def lifespan(app: FastAPI):
    """
    生命周期

    Args:
        app (FastAPI): _description_
    """
    from fastapi_cache import FastAPICache

    from forward.config import get_settings
    from forward.dependencies.cache import custom_key_builder, redis_be
    from forward.dependencies.database import db

    settings = get_settings()
    print("db", db.url)
    await db.connect()
    FastAPICache.init(
        redis_be, prefix=settings.redis_prefix, key_builder=custom_key_builder
    )

    yield
    await db.disconnect()


def configure_static(app: FastAPI):
    """配置静态资源"""

    settings = get_settings()
    # 上传路径创建
    if not os.path.exists(settings.upload_directory):
        os.makedirs(settings.upload_directory)
    # 上传路径配置
    app.mount(
        settings.upload_path,
        StaticFiles(directory=settings.upload_directory),
        name="upload",
    )
    # 静态资源路径配置
    if settings.enabled_static:
        app.mount(
            settings.static_path,
            StaticFiles(directory=settings.static_directory),
            name="static",
        )


def configure_swagger_ui(app: FastAPI):
    """配置swagger ui"""

    from fastapi.openapi.docs import get_swagger_ui_html

    print("configure_swagger_ui", app.openapi_url)

    @app.get("/openapi.json", include_in_schema=False)
    async def get_openapi():
        return app.openapi()

    @app.get(
        "/docs",
        include_in_schema=False,
    )
    async def custom_swagger_ui_html():

        return get_swagger_ui_html(
            openapi_url=app.openapi_url if app.openapi_url else "/openapi.json",
            title=app.title,
            swagger_favicon_url="./static/swaggerUI/favicon-32x32.png",
            swagger_ui_parameters=app.swagger_ui_parameters,
            swagger_js_url="./static/swaggerUI/swagger-ui-bundle.js",
            swagger_css_url="./static/swaggerUI/swagger-ui.css",
        )


def create_app() -> FastAPI:
    """app初始化函数

    Returns:
        FastAPI: _description_
    """
    app = FastAPI(root_path="/api", lifespan=lifespan)
    configure_static(app)
    configure_swagger_ui(app)
    return app


# 初始化logger
logger = setup_logger()
app = create_app()
app.mount(path="/h5", app=create_h5(), name="h5")
app.mount(path="/admin", app=create_admin(), name="admin")
